<template>
	<view class="container"></view>
</template>

<script>
	import {
		dateUtils,
		authTokenUtil,
		validLoginToken
	} from "../../common/util.js"
export default {
	data() {
		return {};
	},
	methods: {
		receiveSocketMessage: function (msg) {
			console.log(msg, 999);
		},
		sendSocketMessage: function (msg) {
			uni.sendSocketMessage({
				data: `${JSON.stringify({ arguments: [msg], target: 'SendMessage', type: 1 })}${String.fromCharCode(0x1e)}`
			});
		},
		connectSocket: function () {
			let _this = this;
			console.log('connectSocket');
			//signalr得连接地址并携带token
			// let url = "ws://xxx/xxxHub"+ '?access_token=xxxx';
			let url = 'ws://192.168.1.124:3003/hubs/sysmsghub'; //这里 ws对的是Http://localhost:5000地址 ； wss对的是Http://localhost:5001

			//开始连接
			uni.connectSocket({
				url: url,
				method: 'GET',
				success: function () {}
			});
			//连接成功
			uni.onSocketOpen(function (res) {
				console.log('WebSocket连接已打开！');

				//告诉服务器使用 JSON 的形式进行消息的序列化
				uni.sendSocketMessage({
					data: `{"protocol":"json", "version":1}${String.fromCharCode(0x1e)}`
				});
				//测试发送消息
				   // _this.sendSocketMessage('12313');
			});
			//连接失败
			uni.onSocketError(function (res) {
				console.log(res, 'WebSocket连接打开失败，1秒后重连！');
				setTimeout(function() {							
					//开始连接
					uni.connectSocket({
						url: url,
						method: 'GET',
						success: function () {}
					});
				}, 1000);
			});
			//接收到服务端消息
			uni.onSocketMessage(function (res) {
				var msg = res.data.replace(String.fromCharCode(0x1e), ''); //替换消息结束符			
				
				let msgData = JSON.parse(msg);
				//接收指定消息（这里为服务端得ReceiveMessage得消息，msgData.type === 1 为固定值表示调用客户端的一个方法）
				if (msgData.type === 1 && msgData.target == 'ReceiveMessage') {
					console.log('收到服务器内容：' + JSON.stringify(msgData.arguments[0]));
					_this.receiveSocketMessage(msgData.arguments[0]);
				}
			});
			//断开时得方法
			uni.onSocketClose(function (res) {
				console.log('WebSocket 已关闭！');
			});
		},
		init: function () {
			let _this = this;
			validLoginToken(null, () => {
				uni.reLaunch({
					url: "/pages/account/login"
				})
			})
			_this.connectSocket();
		}
	},
	onShow() {
		// let _this = this;
		// _this.init();
	},
	created() {
		let _this = this;
		_this.init();
	}
};
</script>

<style>
.container {
	display: flex;
	flex-direction: column;
	justify-content: flex-start;
	align-items: stretch;
}
</style>
